package main

import (
	"bytes"
	"fmt"
	"os"
	"runtime"
	"strings"

	"gitee.com/mkwchecking/sr-admin/cmd"

	_ "gitee.com/mkwchecking/sr-admin/cmd/apisvr"
	_ "gitee.com/mkwchecking/sr-admin/cmd/domain"
	_ "gitee.com/mkwchecking/sr-admin/cmd/list"
	_ "gitee.com/mkwchecking/sr-admin/cmd/migrate"

	// engine
	_ "gitee.com/linxing_3/sr-core/plugins/storage/database/driver/sqlite3"
	"gitee.com/linxing_3/sr-core/utils/style"
)

//go:generate swag init --parseDependency --parseDepth=7 --instanceName swagger -o ./docs

type ErrorHandler string

const (
	ErrorHandlerPanic ErrorHandler = "panic"
	ErrorHandlerExit  ErrorHandler = "exit"
	ErrorHandlerPrint ErrorHandler = "print"
)

func getErrorHandlerType() ErrorHandler {
	return ErrorHandler(strings.ToLower(os.Getenv("SR_ERR_HANDLER")))
}

// 打印错误的堆栈信息
func PrintStackTrace(err error) {
	// 创建一个缓冲区用于存储堆栈信息
	buf := bytes.NewBuffer(nil)

	// 获取当前goroutine的堆栈信息
	for i := 0; ; i++ {
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		fmt.Fprintf(buf, "%d: %s:%d (0x%x)\n", i, file, line, pc)
	}

	// 打印堆栈信息
	fmt.Println(buf.String())
}
func Run() {
	main()
}
func main() {

	if err := cmd.RootCmd().Execute(); err != nil {
		// 处理错误
		fmt.Println(style.Red("Error"), err.Error())

		switch getErrorHandlerType() {
		case ErrorHandlerExit:
			fmt.Println(style.Red("Error"), err.Error())
			os.Exit(1)
		case ErrorHandlerPanic:
			panic(err)
		default:
			PrintStackTrace(err)
		}
	}
}
